#include "Packet.h"

#include <packet/XMPPError.h>
#include <packet/PacketExtension.h>


std::string Packet::ID_NOT_AVAILABLE = "ID_NOT_AVAILABLE";
std::string Packet::DEFAULT_XML_NS = "";
std::string Packet::prefix = StringUtils::randomString(5) + "-";
std::string Packet::DEFAULT_LANGUAGE = "zh_CN.UTF8";
long Packet::id = 0;

Packet::Packet() : 
	xmlns(DEFAULT_XML_NS),
	error(NULL)
{}


std::string Packet::nextID() {
	std::string s(id++);
	return prefix + s;
}


void Packet::setDefaultXmlns(std::string & defaultXmlns) {
	DEFAULT_XML_NS = defaultXmlns;
}


std::string Packet::getPacketID() {
	if (ID_NOT_AVAILABLE == packetID) {
		return "";
	}

	if (packetID.empty()) {
		packetID = nextID();
	}
	return packetID;
}


void Packet::setPacketID(std::string & packetID) {
	this.packetID = packetID;
}


std::list<PacketExtension*> Packet::getExtensions() {
	return packetExtensions;
}


PacketExtension * Packet::getExtension(std::string & elementName, std::string & nameSpace) {
	if (!nameSpace.empty()) {
		for (std::list<PacketExtension*>::iterator it = packetExtensions.begin();
				it != packetExtensions.end(); it ++ ) {
			PacketExtension * ext = *it;
			if ((elementName.empty() || elementName == ext->getElementName())
					&& nameSpace == ext->getNamespace()) {
				return ext;
			}
		}
	}
	return NULL;
}


void Packet::addExtension(PacketExtension * extension) {
	packetExtensions.push_back(extension);
}


void Packet::removeExtension(PacketExtension * extension)  {
	packetExtensions.remove(extension);
}


std::string Packet::getProperty(std::string & name) {
	return properties[name];
}


void Packet::setProperty(std::string & name, std::string & value) {
	properties[name] = value;
}


void deleteProperty(std::string & name) {
	properties.erase(name);
}


std::list<std::string> Packet::getPropertyNames() {
	std::list<std::string> l;
	for (std::map<std::string,std::string>::iterator it = properties.begin();
			it != properties.end(); it ++) {
		l.push_back(it->first);
	}
	return l;
}


std::string Packet::getExtensionsXML() {
	std::string buf;
	// Add in all standard extension sub-packets.
	for (std::list<PacketExtension*>::iterator it = packetExtensions.begin();
			it != packetExtensions.end(); it ++) {
		buf.append((*it)->toXML());
	}
    return buf;
}


std::string Packet::getXmlns() {
	return xmlns;
}


std::string Packet::parseXMLLang(std::string & language) {
	if (language.empty()) {
		language = DEFAULT_LANGUAGE;
	}
	return language;
}


std::string Packet::getDefaultLanguage() {
	return DEFAULT_LANGUAGE;
}	


int Packet::hashCode() { return 0; };
